
public class Example5 {

	public static void main(String[] args) {
		int[] nums1 = {-23,1,3,45,67,120};
		int[] nums2 = {-123,-23,0,1,5,45,57,120,230,455};
		int[] jsNums = join(nums1,nums2);
		System.out.println("这是交集：");
		myPrintArray(jsNums);
		System.out.println();
		System.out.println("这是并集：");
		int[] bsNums = merge(nums1,nums2);
		myPrintArray(bsNums);
	}
	public static int[] join(int[] ns1,int[] ns2) {
		int[] result1 = new int[ns1.length + ns2.length];
		int i,j;
		int k=0;
		for(i=0,j=0;i<ns1.length && j<ns2.length;) {
			if(ns1[i] <ns2[j]) {	
				i++;
			}else if(ns1[i] > ns2[j]) {
				j++;
			}else {
				result1[k] = ns1[i];
				j++;
				i++;
				k++;
			}
		}
		int[] result = new int[k];
		for(int m=0;m<k;m++) {
			result[m] = result1[m];
		}
		return result;
		
		
	}
	public static int[] merge(int[] ns1,int[] ns2) {
		int[] result1 = new int[ns1.length + ns2.length];
		int i,j;
		int k = 0;
		for(i=0,j=0; i<=ns1.length || j<=ns2.length;) {
			if(i==ns1.length) {
				while(j<ns2.length) {
					result1[k] = ns2[j];
					k++;
					j++;
				}
				break;
			}
			if(j==ns2.length) {
				while(i<ns1.length) {
					result1[k] = ns2[i];
					k++;
					i++;
				}
				break;
			}
			if(ns1[i] < ns2[j]) {
				result1[k] = ns1[i];
				k++;
				i++;
			}else if(ns1[i] > ns2[j]) {
				result1[k] = ns2[j];
				k++;
				j++;
			}else if( ns1[i] == ns2[j]) {
				result1[k] = ns2[j];
				k++;
				j++;
				i++;
			}
			
		}
		int[] result = new int[k];
		for(int m=0;m<k;m++) {
			result[m] = result1[m];
		}
		return result;
		
	}
	public static void myPrintArray(int[] nums) {
		for(int i=0; i<nums.length; i++) {
			System.out.print(nums[i]+"\t");
		}
	}
}
